package com.boot.ys.mybatisplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.boot.ys.mybatisplus.entity.Caidan;
import com.boot.ys.mybatisplus.entity.dto.CaiDanDto;
import com.boot.ys.mybatisplus.mapper.CaidanMapper;
import com.boot.ys.mybatisplus.service.CaidanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Yang Sheng
 * @since 2022-08-04
 */
@Service
public class CaidanServiceImpl extends ServiceImpl<CaidanMapper, Caidan> implements CaidanService {

    @Autowired
    private CaidanMapper caidanMapper;

    @Override
    public List<Caidan> selectAll() {
        List<Caidan> caidansList = caidanMapper.selectList(null);
        Page rolePage = new Page(1, 10);
        Page page = caidanMapper.selectPage(rolePage, null);
        return caidansList;
    }


    @Override
    public int addCaidan(Caidan caidan) {
        caidan.setTm(new Date());
        int isSum = caidanMapper.insert(caidan);
        return isSum;

    }


    @Override
    public int deleteById(Caidan caidan) {

        int isSum = caidanMapper.deleteById(caidan.getId());
        return isSum;
    }

    @Override
    public int updateCaidan(Caidan caidan) {
        caidan.setTm(new Date());
        int i = caidanMapper.updateById(caidan);
        return i;
    }


    public List<CaiDanDto> getTree(CaiDanDto caiDanDto ) {
        //1.查出所有分类
        List<CaiDanDto> entities = baseMapper.selectListD();
//        //2)、找到所有的一级分类
        List<CaiDanDto> level1Caidan = entities.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentid() == 0;
        }).map((menu)->{
            menu.setChildren(getchildren(menu,entities));
            return menu;
        }).collect(Collectors.toList());
        return level1Caidan;
    }
    //递归查找所有菜单的子菜单
    private List<CaiDanDto> getchildren(CaiDanDto root,List<CaiDanDto> all){
        List<CaiDanDto> children = all.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentid() == root.getId();
        }).map((categoryEntity) -> {
            //1.找到子菜单
            categoryEntity.setChildren(getchildren(categoryEntity,all));
            return categoryEntity;
        }).collect(Collectors.toList());
        return children;
    }

}
